package com.lu.pojo.thread;

/**
 * @author luzhenfang
 * @date 2020 05 24
 * @description 生产者消费者模型
 *  缓冲区解决(管程法)
 *
 */
public class TestPC {

    public static void main(String[] args) {
        SynContainer container = new SynContainer();
        new Productor(container).start();
        new Consumer(container).start();
    }
}
// 生产者模型
class Productor extends Thread{
    SynContainer container;
    public Productor(SynContainer container){
        this.container=container;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            container.push(new Chicken(i));
            System.out.println("叮咚~编号为"+i+"的鸡已生产好！");
        }

    }
}

// 消费者模型
class Consumer extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("咣当~编号为"+container.pop().id+"的鸡已被消费!");
        }
    }

    SynContainer container;
    public Consumer(SynContainer container) {
        this.container=container;
    }
}


// 产品
class Chicken{
    int id;

    public Chicken(int id) {
        this.id = id;
    }
}

// 缓冲区
class SynContainer{
    // 容器大小
    Chicken[] chickens =new Chicken[10];
    int count =0;
    public synchronized void push(Chicken chicken){
        // 如果容器满了 就等待消费者消费
        if (count==chickens.length){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        chickens[count] =chicken;
        count++;
        // 通知消费者消费等待生产
        this.notifyAll();
    }
    public synchronized Chicken pop(){
        if(count==0){
            // 等待生产者生产 消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        Chicken chicken = chickens[count];
        // 通知生产者 快点生产
        this.notifyAll();
        return chicken;
    }
}
